package com.multi.config;

import javax.sql.DataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Slf4j
@Configuration
@MapperScan(basePackages = {"com.multi.mapper.slave"},
        sqlSessionFactoryRef = "SlaveSqlSessionFactory")
public class SlaveDsConfig {
    @Bean(name = "SlaveDs")
    @Qualifier("SlaveDs")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource clickHouseDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "SlaveSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("SlaveDs") DataSource dataSource)
            throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mappers/slave/*.xml"));
        log.info("------------------------------------------SlaveDs 配置成功");
        return sessionFactoryBean.getObject();
    }

}
